package com.share.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@EnableAspectJAutoProxy
@Slf4j
public class RequestLoggingAspect {

    /**
     * 指定切点表达式，根据包名或者其他条件选择性地记录日志
     *
     * @param joinPoint joinPoint
     */
    @Before("execution(* com.cherry.controller..*(..))")
    public void logRequestInfo(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String methodName = joinPoint.getSignature().getName();
        String url = request.getRequestURL().toString();
        String realIp = request.getHeader("X-Real-IP");
        log.info("----aspect-----Method Name: {}, URL: {}, IP Address: {}", methodName, url, realIp);
    }
}